
//获取应用实例
const global = getApp().globalData;
const Api = global.Api;
const util = global.util;
const wxApi = global.wxApi;
const store = global.store;
const getUserInfo = global.getUserInfo;

Page({
  data: {
    banners: [],
    memories: [],
    subjects: [],
    searchbarOpacity: 0,
    searchbarHidden: false,
    hasUnread: false,
    subjectsLookedAccounts: null
  },
  onShow() {
    this.timer = setTimeout(() => {
      wx.hideNavigationBarLoading();
      clearTimeout(this.timer);
      this.timer = null;
    }, 5000);
    let accounts = store.getAccountOfSubjectsLooked()
    this.setData({
      subjectsLookedAccounts: accounts
    })
  },
  onLoad (options) {
    this.userInfo = getUserInfo( data => {
      if ( !this.userInfo )
        this.userInfo = data;
        this.init();
    } );
    if ( !this.userInfo ) {
      return;
    }
    this.init();  
  },
  init( fn ) {
    let self = this;
    this.loadAppData( () => {
      fn && fn()
    });
    this.loadSubjects();
    this.loadUnreadMsgCounts();
    if ( global.isFirstOpen ) {
      this.showGuidence();
    }
  },
  onShareAppMessage( res ) {
    if (res.from === 'button') {
    }
    let userPhone = this.userInfo.encryptedData;
    let self = this;
    return {
      title: '邀你一起高效学习',
      path: '/pages/index/index?userPhone=' + userPhone,
      imageUrl: 'https://omj0etkcd.qnssl.com/appBanner/banner3.jpg',
      success() {
        if ( self.subjectId ) {
          Api.fireSubject( self.subjectId, (res, code) => {
          } )
        }
      },
      fail() {
        console.log( 'fail' )
      }
    }
  },
  onSubjectTaped(e) {
    let subject = e.detail;
    let subjectId = subject.id;
    this.subjectId = subjectId;
    let params = {
      type: '2',
      id: this.subjectId,
      name: subject.name
    }
    console.log('选中：' + subject.name);
    console.log(subject);
    if (!subject.textbooksCount) {
      Api.subjectAvalible( subjectId, avalible => {
        console.log( avalible );
        if ( avalible ) {
          wxApi.navigateTo("../common/webview/webview", {
            src: subject.linkUrl + "?wxApp"
          })
        } else {
          this.setData({
            promptShow: true
          })
        }
      } )
    } else {

      store.addCountOfSubjectLooked(this.subjectId, subject.publishTime);
      wxApi.navigateTo('../books/books', params);
    }
  },
  /**
   * 加载首页所需数据
   */
  loadAppData( fn ) {
    Api.getAppIndex(data => {
      let memoryVideos = data.memoryVideos;
      let newMemoryVideos = [];
      console.log(data);
      for ( let i = 0, len = memoryVideos.length; i < len; i ++ ) {
        let memoryObj = memoryVideos[ i ];
        let img = memoryObj.img;
        memoryObj.smallImg = img.split('.png')[0] + '-small.png';
        memoryObj.padImg = img.split('.png')[0] + '-pad.png';
        newMemoryVideos.push( memoryObj );
      }
      this.setData({
        banners: data.banners,
        memories: newMemoryVideos
      });
      fn && fn();
    });
  },
  /**
   * 加载九大学科数据
   */
  loadSubjects( fn ) {
    Api.getSubjects(data => {
      console.log('subjects')
      console.log(data);
      this.setData({
        subjects: data
      })
      fn && fn()
    })
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    let self = this;
    this.searchbarShow();
    this.init(() => {
      let timer = setTimeout(() => {
        self.searchbarHidden();
        clearTimeout( timer );
        timer = null;
      }, 500);
      wx.stopPullDownRefresh();
    })
  },
  searchbarShow() {
    this.setData({
      searchbarHidden: true
    })
  },
  searchbarHidden() {
    this.setData({
      searchbarHidden: false
    })
  },
  /**
   * 监听页面滚动
   * @param {Object} scrollObj
   */
  onPageScroll(scrollObj) {
    let scrollTop = scrollObj.scrollTop;
    if (scrollTop < 80) {
      this.setData({
        'searchbarOpacity': scrollTop / 60
      })
    } else {
      this.setData({
        'searchbarOpacity': 1
      })
    }
  },
  loadUnreadMsgCounts( fn ) {
    Api.unreadMsgCounts( unread => {
      let count = unread.eventUnreadCount + unread.orgUnreadCount + unread.sysUnreadCount;
      this.setData({
        hasUnread: count > 0
      })
      fn && fn()
    } )
  }
})
